#include "voda.h"
#include "utils.h"

namespace voda
{
	bool toString (JSContext* cx, JSString * jsStr, std::string & str)
	{
		if (!jsStr)
		{
			return false;
		}

		str.clear();

		size_t const length = JS_GetStringEncodingLength (cx, jsStr);
		if (0 == length)
		{
			return true;
		}

		str.reserve (length);
		str.resize (length, 0);

		size_t const copied = JS_EncodeStringToBuffer (cx, jsStr, &str[0], length);

		return (length == copied);
	}

	bool toString (JSContext* cx, jsval const & val, std::string & str)
	{
		if (!JSVAL_IS_STRING (val))
		{
			return false;
		}

		JSString * const jsStr = JSVAL_TO_STRING (val);
		if (!jsStr)
		{
			return false;
		}

		return toString (cx, jsStr, str);
	}

	JSString * toJSString (JSContext* cx, char const * str, size_t const len)
	{
		return JS_NewStringCopyN (cx, str, len);
	}

	JSString * toJSString (JSContext* cx, std::string const & str)
	{
		return JS_NewStringCopyN (cx, str.c_str (), str.size ());
	}

}//namespace voda